package com.hci.pwf;

import java.util.Calendar;
import java.util.Date;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;   
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TimePicker;


import android.widget.TextView;

public class SettingActivity extends Activity {
	private int myHour, myMinute;
	static final int ID_TIMEPICKER = 1;
	Button btnTimeEDlg;
	TextView tvTimeShow;
	public static final String SETTING_INFOS = "SETTING_Infos";  
	public static final String STR_GENDERRADIO = "STR_GENDERRADIO";  
	public static final String STR_PERFERENCE_WIND = "STR_PERFERENCE_WIND"; 
	public static final String STR_PERFERENCE_HUMIDITY="STR_PERFERENCE_HUMIDITY";
	public static final String STR_TIME="STR_TIME";
	public static final String STR_ALARM = "STR_ALARM";  
	public static final String STR_PREDICTION_MODE= "STR_PREDICTION_MODE";  
	 private Calendar c = Calendar.getInstance();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
 
		btnTimeEDlg = (Button) findViewById(R.id.btnSetTime);
		btnTimeEDlg.setOnClickListener(timePickerButtonOnClickListener);
		//read the setting from shared preferences file
		 SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0); 
		 String gender = settings.getString(STR_GENDERRADIO, ""); 
         setGender(gender);
         String preference_wind=settings.getString(STR_PERFERENCE_WIND, "");
         setPerferenceWind(preference_wind);
         String preference_humidity=settings.getString(STR_PERFERENCE_HUMIDITY, "");
		 setPerferenceHumidity(preference_humidity);
		 String remindtime=settings.getString(STR_TIME, "");
		 setRemindTime(remindtime);
		 String alermornot=settings.getString(STR_ALARM, "");
		 setAlarm(alermornot);
		 String prediction_mode=settings.getString(STR_PREDICTION_MODE, "");
		 setPredictionMode(prediction_mode);
         Button button_save = (Button) findViewById(R.id.Button_Save);
		 Button button_return=(Button)findViewById(R.id.Button_Return);
		 button_save.setOnClickListener(new View.OnClickListener()
	        {
	            public void onClick(View v)
	            {   
	            	showConfirmDialog();
	            }
	        });   
		 button_return.setOnClickListener(new View.OnClickListener()
	        {
	            public void onClick(View v)
	            {   
	    		// return to main view
	    			Intent intententering = new Intent(SettingActivity.this,
	    			MainActivity.class);
	    			startActivityForResult(intententering, 0);
	            }
	        });   
		
	}
    private void showConfirmDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("sure to save this setting ?");
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// save the setting of users into the sharedpreferences fine
    			SharedPreferences settings=getSharedPreferences(SETTING_INFOS,0);
    			SharedPreferences.Editor editor=settings.edit();
    			RadioButton gender_Radiobutton_male=(RadioButton)findViewById(R.id.Gender_RadioButton_male);
    			RadioButton gender_Radiobutton_female=(RadioButton)findViewById(R.id.Gender_RadioButton_female);
    			if(gender_Radiobutton_male.isChecked()){
    				editor.putString(STR_GENDERRADIO, "male");
    			}else if(gender_Radiobutton_female.isChecked()){
    				editor.putString(STR_GENDERRADIO, "female");
    			}
    			CheckBox wind_checkbox=(CheckBox)findViewById(R.id.Wind_CheckBox);
    			CheckBox humidity_checkbox=(CheckBox)findViewById(R.id.Humidity_CheckBox);
    			if(wind_checkbox.isChecked()){
    				editor.putString(STR_PERFERENCE_WIND,"true");
    			}else{
    				editor.putString(STR_PERFERENCE_WIND,"false");
    			}
    		      if(humidity_checkbox.isChecked()){
    		    	  editor.putString(STR_PERFERENCE_HUMIDITY, "true");  
    		      }else{
    		    	  editor.putString(STR_PERFERENCE_HUMIDITY, "false");  
    		      }
    		      TextView tvshowtime=(TextView)findViewById(R.id.tvShowTime);
    		      
    			editor.putString(STR_TIME, tvshowtime.getText().toString());
    			RadioButton alerm_radiobutton_true=(RadioButton)findViewById(R.id.Alerm_RadioButton_ture);
    			RadioButton alerm_radiobutton_false=(RadioButton)findViewById(R.id.Alerm_RadioButton_false);
    			if(alerm_radiobutton_true.isChecked()){
    				editor.putString(STR_ALARM, "true");
    			}else if(alerm_radiobutton_false.isChecked()){
    				editor.putString(STR_ALARM, "false");
    			}
    			RadioButton prediction_mode_simple=(RadioButton)findViewById(R.id.Prediction_Mode_RadioButton_Simple);
    			RadioButton prediction_mode_showfourdays=(RadioButton)findViewById(R.id.Prediction_Mode_RadioButton_ShowFourDays);
    			if(prediction_mode_simple.isChecked()){
    				editor.putString(STR_PREDICTION_MODE, "simple");
    			}else if(prediction_mode_showfourdays.isChecked()){
    				editor.putString(STR_PREDICTION_MODE, "showfourdays");
    			}
    			
    			if(editor.commit()){
    				setResult(Activity.RESULT_OK);
    			}
    			finish();
    			//set the alarm time 
    			if(tvshowtime.getText().toString()!=null){
    				Intent startIntent = new Intent(AlarmReceiver.ALARM_ALERT);
        			boolean alarmOrNot=false;
        			if(alerm_radiobutton_true.isChecked()){
        				alarmOrNot=true;
        			}else if(alerm_radiobutton_false.isChecked()){
        				alarmOrNot=false;
        			}
        			startIntent.putExtra("AlarmOrNot", alarmOrNot);
        			PendingIntent startSender = PendingIntent.getBroadcast(SettingActivity.this, 0, startIntent, 0);
        			//set the alarm 
        		    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);   
                     am.setRepeating(AlarmManager.RTC_WAKEUP,getSettingTimeMillis() ,24 * 60 * 60 * 1000,startSender  );

    			}	
				//retrun to main page
    			Intent intententering = new Intent(SettingActivity.this,
    					MainActivity.class);
    			startActivityForResult(intententering,0);
    			finish();

			}

			private long getSettingTimeMillis() {
				long settingTimeMillis=0;
			   
			    Calendar ca=Calendar.getInstance();
			    ca.setTimeInMillis(System.currentTimeMillis());
			    if(ca.before(c)){
			    	settingTimeMillis= c.getTimeInMillis();
			    }else{
			    	settingTimeMillis=c.getTimeInMillis()+24 * 60 * 60 * 1000;
			    }
			
				/*Date dateNow = new Date();
				String[] aryTemp1 = time.split(":"); 
				String strHour = aryTemp1[0];
				String[] aryTemp2=aryTemp1[1].trim().split(" ");
				String strMinute=aryTemp2[0];
				int intHour=Integer.valueOf(strHour);
				int intMinute=Integer.valueOf(strMinute);
		    	long hour = intHour-dateNow.getHours();
		    	long min = intMinute-dateNow.getMinutes();
		    	long second = dateNow.getSeconds();
		    	if(hour<=0||min<=0){
		    		settingTimeMillis=dateNow.getTime() + (hour*60 + min)*60*1000 - second*1000+24*60*60*1000;
		    	}else{
		    		settingTimeMillis=dateNow.getTime() + (hour*60 + min)*60*1000 - second*1000;
		    	}*/
		        
		    	return settingTimeMillis;
			}
		});
		builder.setNeutralButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						//stay on this setting page
						

					}
				});
		Dialog dialog = builder.create();
		dialog.show();
	}
	private void setPredictionMode(String prediction_mode) {
		RadioButton prediction_mode_simple=(RadioButton)findViewById(R.id.Prediction_Mode_RadioButton_Simple);
		RadioButton prediction_mode_showfourdays=(RadioButton)findViewById(R.id.Prediction_Mode_RadioButton_ShowFourDays);
		if(prediction_mode.equals("simple")){
			prediction_mode_simple.setChecked(true);
			prediction_mode_showfourdays.setChecked(false);
		}else if(prediction_mode.equals("showfourdays")){
			prediction_mode_simple.setChecked(false);
			prediction_mode_showfourdays.setChecked(true);
		}
	}

	private void setAlarm(String alermornot) {
		RadioButton alerm_radiobutton_true=(RadioButton)findViewById(R.id.Alerm_RadioButton_ture);
		RadioButton alerm_radiobutton_false=(RadioButton)findViewById(R.id.Alerm_RadioButton_false);
		if(alermornot.equals("true")){
			alerm_radiobutton_true.setChecked(true);
			alerm_radiobutton_false.setChecked(false);
		}else if(alermornot.equals("false")){
			alerm_radiobutton_true.setChecked(false);
			alerm_radiobutton_false.setChecked(true);
		}
	}

	private void setRemindTime(String remindtime) {
		TextView tvshowtime=(TextView)findViewById(R.id.tvShowTime);
		tvshowtime.setText(remindtime);
		
	}

	private void setPerferenceHumidity(String preference_humidity) {
		CheckBox humidity_checkbox=(CheckBox)findViewById(R.id.Humidity_CheckBox);
		if(preference_humidity.equals("true")){
			humidity_checkbox.setChecked(true);
		}else{
			humidity_checkbox.setChecked(false);
		}
		
	}

	private void setPerferenceWind(String preference_wind) {
		CheckBox wind_checkbox=(CheckBox)findViewById(R.id.Wind_CheckBox);
		if(preference_wind.equals("true")){
			wind_checkbox.setChecked(true);
		}else{
			wind_checkbox.setChecked(false);
		}
		
	}

	private void setGender(String gender) {
		 RadioButton gender_Radiobutton_male=(RadioButton)findViewById(R.id.Gender_RadioButton_male);
			RadioButton gender_Radiobutton_female=(RadioButton)findViewById(R.id.Gender_RadioButton_female);
		 if(gender.equals("male")){
			 gender_Radiobutton_male.setChecked(true);
			 gender_Radiobutton_female.setChecked(false);
		 }else if(gender.equals("female")){
			 gender_Radiobutton_male.setChecked(false);
			 gender_Radiobutton_female.setChecked(true);
		 }
		
	}

	private Button.OnClickListener timePickerButtonOnClickListener = new Button.OnClickListener() {
		public void onClick(View v) {
			c.setTimeInMillis(System.currentTimeMillis()); 
			myHour = c.get(Calendar.HOUR_OF_DAY);
			myMinute = c.get(Calendar.MINUTE);
			showDialog(ID_TIMEPICKER);
		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_TIMEPICKER:
			return new TimePickerDialog(this, myTimeSetListener, myHour,
					myMinute, false);
		default:
			return null;
		}

	}

	private TimePickerDialog.OnTimeSetListener myTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			c.setTimeInMillis(System.currentTimeMillis()); 
			c.set(Calendar.HOUR_OF_DAY,hourOfDay); 
			c.set(Calendar.MINUTE,minute); 
			c.set(Calendar.SECOND,0); 
			c.set(Calendar.MILLISECOND,0); 
			tvTimeShow = (TextView) findViewById(R.id.tvShowTime);
			tvTimeShow.setText( Integer.toString(hourOfDay) + ":"
					+ Integer.toString(minute) +" "+ "(24h)");

		}
	};
};


